package rs.etf.kdp.server;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class InterthreadBuffer {
	
	private final Lock lock = new ReentrantLock();
	private final Condition full = lock.newCondition();
	private final Condition empty = lock.newCondition();
	
	private EventFromWS[] messages;
	private int rear, front, inBuffer;
	private int length;
	
	public InterthreadBuffer(int size)
	{
		messages = new EventFromWS[size];
		rear = front = inBuffer = 0;
		length = size;
	}
	
	public InterthreadBuffer()
	{
		this(30);
	}
	
	public void putEventFromWS(EventFromWS msg)
	{
		lock.lock();
		try
		{
			while(inBuffer==length) 
			{
				try {
					full.await();
				} catch (InterruptedException e) {
					System.out.println("putMessageError");
				}
			}
			messages[front] = msg;
			front = (front + 1) % length;
			inBuffer++;
			empty.signal();
			
		} finally
		{
			lock.unlock();
		}
	}
	
	
	public EventFromWS getMessage()
	{
		EventFromWS msg;
		lock.lock();
		try
		{
			while(inBuffer==0)
			{
				try {
					empty.await();
				} catch (InterruptedException e) {
					System.out.println("getMessageError");
				}
			}
			msg = messages[rear];
			rear = (rear + 1) % length;
			inBuffer--;
			full.signal();
		} finally
		{
			lock.unlock();
		}
		return msg;
	}
}
